import React, { useState, useEffect } from 'react';
import {
  Button, Modal, Icon, message,
} from 'antd';
import timeFormat from 'utils/time';
import TableWithSearch from 'components/TableWithSearch';
import ConfirmDeleteButton from 'components/ConfirmDeleteButton';
import { deleteDeployment, publishDeployment } from 'services/deployment';
import { listImage } from 'services/image';
import { defaultRejectHandler } from 'utils/http';
import CreationForm from './creation/Form';
import Details from './details/Details';


export default function ServiceTable({ dataSource, updateData }) {
  const [detailsState, setDetailsState] = useState({ visible: false, conditions: null, env: null });
  const [createVisible, setCreateVisible] = useState(false);
  const [imageList, setImageList] = useState([]);

  useEffect(() => {
    listImage().then((data) => {
      const images = data.map((item) => item.tag);
      setImageList(images);
    }, defaultRejectHandler);
  }, []);

  const formattedData = dataSource.map((item) => ({
    ...item,
    replicas: item.replicas || 0,
    availableReplicas: item.availableReplicas || 0,
    creationTimestamp: timeFormat(item.creationTimestamp),
  }));

  const closeCreationModal = () => setCreateVisible(false);

  const columns = [
    {
      title: '服务名称',
      key: 'name',
      render: (record) => {
        const { name, availableReplicas, replicas } = record;
        const healthy = availableReplicas === replicas;
        return healthy
          ? (
            <span>
              {
                // tried using theme="filled" on Icon but it didn't work
              }
              <Icon type="check" style={{ color: 'green', marginRight: 3 }} />
              {name}
            </span>
          )
          : (
            <span>
              <Icon type="exclamation" style={{ color: 'yellow', marginRight: 3 }} />
              {name}
            </span>
          );
      },
    },
    {
      title: '服务所使用的镜像名称',
      dataIndex: 'image',
      key: 'image',
    },
    {
      title: '创建时间',
      dataIndex: 'creationTimestamp',
      key: 'creationTimestamp',
    },
    {
      title: '副本数目',
      key: 'replicas',
      render: (record) => <span>{`${record.availableReplicas} / ${record.replicas}`}</span>,
    },
    {
      title: '发布状态',
      dataIndex: 'publishStatus',
      key: 'publishStatus',
      render: (status) => (status ? '已发布' : '未发布'),
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <>
          <Button
            size="small"
            style={{ marginRight: '10px' }}
            onClick={() => setDetailsState({
              visible: true, conditions: record.conditions, env: record.env,
            })}
          >
          详细状态
          </Button>

          <Button
            size="small"
            style={{ marginRight: '10px' }}
            onClick={() => {
              publishDeployment({ name: record.name, publishStatus: !record.publishStatus })
                .then(() => {
                  message.success('操作成功！');
                  updateData();
                }, defaultRejectHandler);
            }}
          >
            {record.publishStatus ? '取消发布' : '发布'}
          </Button>
          <ConfirmDeleteButton
            confirmTitle="确定删除该服务?"
            onConfirm={() => {
              deleteDeployment({ name: record.name }).then(() => {
                message.success('操作成功！');
                updateData();
              }, defaultRejectHandler);
            }}
            buttonText="删除"
          />
        </>
      ),
    },
    {
      title:
  <>
    <Button type="dashed" icon="plus" onClick={() => setCreateVisible(true)} />
    <Button type="dashed" icon="reload" onClick={updateData} />
  </>,
      key: 'add',
      render: () => null,
    },
  ];

  return (
    <>
      <TableWithSearch rowKey="name" dataSource={formattedData} columns={columns} />
      <Modal
        visible={detailsState.visible}
        width={1000}
        title="详情"
        onCancel={() => setDetailsState({ visible: false, data: null })}
        footer={null}
      >
        <Details conditions={detailsState.conditions} env={detailsState.env} />
      </Modal>
      <Modal
        visible={createVisible}
        title="新建部署"
        onCancel={closeCreationModal}
        footer={null}
      >
        <CreationForm
          imageList={imageList}
          updateData={updateData}
          closeModal={closeCreationModal}
        />
      </Modal>
    </>
  );
}
